package com.ddx.service.impl;

import com.ddx.check.CheckShortVideoParamValidate;
import com.ddx.common.enums.ErrorCode;
import com.ddx.common.exception.BusinessException;
import com.ddx.common.util.AliyunVideoUtil;
import com.ddx.common.util.AssertUtil;
import com.ddx.common.util.DateUtil;
import com.ddx.dao.*;
import com.ddx.dto.ShortVideoDto;
import com.ddx.pojo.*;
import com.ddx.service.AdvertService;
import com.ddx.service.ShortVideoService;
import com.ddx.service.UserFollowService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.ws.rs.HEAD;
import java.util.*;

/**
 * @author: liyuxiang
 * @create: 2018-11-10
 */
@Service
public class ShortVideoServiceImpl implements ShortVideoService {
    private static Logger logger = LoggerFactory.getLogger(ShortVideoServiceImpl.class);
    @Autowired
    ShortVideoMapper shortVideoMapper;
    @Autowired
    UserFollowService userFollowService;
    @Autowired
    ShortVideoLikeMapper shortVideoLikeMapper;
    @Autowired
    UserMapper userMapper;
    @Value("${fastdfs.server}")
    String fastdfsServer;
    @Autowired
    AdvertService advertService;
    @Autowired
    UserFollowMapper userFollowMapper;
    @Autowired
    ShortVideoBrowseMapper shortVideoBrowseMapper;


    @Override
    public List<ShortVideo> getListByRecord(ShortVideo shortVideo) {
        List<ShortVideo> list=shortVideoMapper.selectBySelectiveRecord(shortVideo);
        covertList(list,shortVideo.getUserId()==null?null:shortVideo.getUserId().toString());
        return list;
    }

    @Override
    public List<ShortVideo> getUserLikeSV(String userId) {
        List<ShortVideo> list=shortVideoMapper.selectUserLikeSV(userId);
        covertList(list,userId);
        return list;
    }

    // 精彩
    @Override
    public List<ShortVideo> marvellous(ShortVideoDto shortVideoDto) throws Exception {
        logger.info("精彩视频入参{}",shortVideoDto);
        // 验证参数
        CheckShortVideoParamValidate.marvellous(shortVideoDto);
        List<ShortVideo> list=new ArrayList<>();
        String startDate=DateUtil.format(DateUtil.getYesterday(new Date()),DateUtil.YYYYMMDD_HHMMSS);
         list=shortVideoBrowseMapper.selectBrowerDetail(startDate,shortVideoDto.getPageSize()*(shortVideoDto.getPageNo()),shortVideoDto.getPageSize());
        if(list==null||list.size()==0) {
            logger.info("浏览视频为空");
            // 按点赞数排序
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("offset", shortVideoDto.getPageSize() * (shortVideoDto.getPageNo()));
            map.put("limit", shortVideoDto.getPageSize());
            map.put("content", shortVideoDto.getContent());
            map.put("sort", "video_like_num");
            map.put("order", "desc");
            List<ShortVideo> videos=shortVideoMapper.getList(map);
            list.addAll(videos);
        }else if(list.size()<shortVideoDto.getPageSize()){
            logger.info("浏览视频不够一页");
            // 按点赞数排序
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("offset", shortVideoDto.getPageSize() * (shortVideoDto.getPageNo()));
            map.put("limit", shortVideoDto.getPageSize()-list.size());
            map.put("content", shortVideoDto.getContent());
            map.put("sort", "video_like_num");
            map.put("order", "desc");
            List<ShortVideo> videos=shortVideoMapper.getList(map);
            list.addAll(videos);
        }
        covertList(list,shortVideoDto.getUserId()==null?null:shortVideoDto.getUserId().toString());
        return list;
    }

    // 关注
    @Override
    public List<ShortVideo> follow(ShortVideoDto shortVideoDto) throws Exception {
        logger.info("关注视频入参{}",shortVideoDto);
        // 验证参数
        CheckShortVideoParamValidate.follow(shortVideoDto);
        // 关注表查询关注用户ID集合
        List<String> followUserIdList = new ArrayList<>();
        List<UserFollow>  userFollowList = userFollowService.getList4userId(shortVideoDto.getUserId());
        if (userFollowList == null || userFollowList.size() == 0){
            return null;
        }
        for (UserFollow userFollow:userFollowList) {
            followUserIdList.add(userFollow.getFollowId().toString());
        }
        // 根据关注用户ID集合查询列表
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("offset", shortVideoDto.getPageSize()*(shortVideoDto.getPageNo()));
        map.put("limit", shortVideoDto.getPageSize());
        map.put("content", shortVideoDto.getContent());
        map.put("followUserIdList", followUserIdList);
        map.put("sort","create_time");
        map.put("order","desc");
        List<ShortVideo> list=shortVideoMapper.getList(map);
        covertList(list,shortVideoDto.getUserId()==null?null:shortVideoDto.getUserId().toString());
        return list;
    }

    // 类型
    @Override
    public List<ShortVideo> type(ShortVideoDto shortVideoDto) throws Exception {
        logger.info("类型视频入参{}",shortVideoDto);
        // 验证参数
        CheckShortVideoParamValidate.type(shortVideoDto);
        // 安装类型，关键字查询
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("offset", shortVideoDto.getPageSize()*(shortVideoDto.getPageNo()));
        map.put("limit", shortVideoDto.getPageSize());
        map.put("content", shortVideoDto.getContent());
        map.put("type", shortVideoDto.getType());
        map.put("sort", "video_like_num");
        map.put("order", "desc");
        List<ShortVideo> list=shortVideoMapper.getList(map);
        covertList(list,shortVideoDto.getUserId()==null?null:shortVideoDto.getUserId().toString());
        return list;
    }

    @Override
    public Map<String,Object> works(ShortVideoDto shortVideoDto) throws Exception {
        AssertUtil.isNotNull(shortVideoDto.getUserId(), "请传入查询用户");
        Map<String,Object> result=new HashMap<>();
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("userId", shortVideoDto.getUserId());
        param.put("sort","create_time");
        param.put("order","desc");
        List<ShortVideo> list=shortVideoMapper.getList(param);
        result.put("worksNumber",list==null?0:list.size());
        List<Map<String,Object>> maps=new ArrayList<>();
        for(ShortVideo shortVideo:list){
            Map<String,Object> map=new HashMap<>();
            map.put("videoId",shortVideo.getId());
            Map<String,String> video=AliyunVideoUtil.getPlayInfo(shortVideo.getVideoId());
            if(video==null){
                continue;
            }
            map.put("coverUrl",video.get("coverURL"));
            map.put("videoUrl",video.get("playURL"));
            ShortVideoLike record=new ShortVideoLike();
            record.setVideoId(shortVideo.getId());
            List<ShortVideoLike> likeList=shortVideoLikeMapper.selectByRecord(record);
            map.put("pointsNumber",likeList==null?0:likeList.size());
            maps.add(map);
        }
        result.put("videoList",maps);
        return result;
    }

    /**
     * 视频详情页面，传视频ID
     */
	@Override
	public Map<String, Object> detail(ShortVideoDto shortVideoDto)  throws Exception {
	    logger.info("视频详情页面入参={}",shortVideoDto);
		// 返回map
		Map<String,Object> map = new HashMap<String,Object>();
	     // 验证参数
		AssertUtil.isNotNull(shortVideoDto.getId(), "视频ID为空！");

        ShortVideoBrowse insert=new ShortVideoBrowse();
        insert.setVideoId(shortVideoDto.getId());
        insert.setUserId(shortVideoDto.getUserId());
        shortVideoBrowseMapper.insertSelective(insert);

        ShortVideo shortVideo=shortVideoMapper.selectByPrimaryKey(shortVideoDto.getId());
        if(shortVideo == null){
        	throw new BusinessException(ErrorCode.BUSSINESS_ERROR_201,"没有查询到数据");
        }
        Map<String, String> video = AliyunVideoUtil.getPlayInfo(shortVideo.getVideoId());
        shortVideo.setCoverUrl(video.get("coverURL"));
        shortVideo.setVideoUrl(video.get("playURL"));

        Advert advert = advertService.getAdvertByVideoId(shortVideo.getId());
        if(shortVideoDto.getUserId()!=null){
            ShortVideoLike record=new ShortVideoLike();
            record.setUserId(shortVideoDto.getUserId());
            record.setVideoId(shortVideo.getId());
            List<ShortVideoLike> likeList=shortVideoLikeMapper.selectByRecord(record);
            if(likeList==null||likeList.size()==0){
                shortVideo.setIsLike(0);
            }else {
                shortVideo.setIsLike(1);
            }
        }else{
            shortVideo.setIsLike(0);
        }
        User user=userMapper.selectByPrimaryKey(shortVideo.getUserId());
        if(StringUtils.isNotBlank(user.getHeadImage())) {
            if (user.getHeadImage().contains("http")) {
                shortVideo.setImageUrl(user.getHeadImage());
            } else {
                shortVideo.setImageUrl(fastdfsServer + user.getHeadImage());
            }
        }
        shortVideo.setUserName(user.getName());
        if(shortVideoDto.getUserId()!=null){
            UserFollow userFollow = userFollowMapper.selectByUserIdAndFollowId(shortVideoDto.getUserId(), shortVideo.getUserId());
            map.put("follow", !Objects.isNull(userFollow));
        }else{
            map.put("follow", 0);
        }
        map.put("shortVideo", shortVideo);
        map.put("advert", advert);
        return map;
    }

    @Override
    public Map<String, Object> search(Map<String, Object> map) throws Exception {
	    if(map.get("content")==null||map.get("pageNo")==null||map.get("pageSize")==null){
	        throw new BusinessException(ErrorCode.BUSSINESS_ERROR_201);
        }
        Map<String,Object> result=new HashMap<>();
        Integer pageNo= Integer.parseInt(map.get("pageNo").toString());
        Integer pageSize= Integer.parseInt(map.get("pageSize").toString());
        String type=map.get("type")==null?null:map.get("type").toString();
        if(type==null||type.equals("person")){
            List<User> users=userMapper.search(map.get("content").toString(),pageNo,pageSize);
            for(User user:users){
                if(StringUtils.isNotBlank(user.getHeadImage())) {
                    if (user.getHeadImage().contains("http")) {
                        user.setHeadImage(user.getHeadImage());
                    } else {
                        user.setHeadImage(fastdfsServer + user.getHeadImage());
                    }
                }
            }
            result.put("searchs",users);
        }else{
            Map<String,Object> video=new HashMap<>();
            video.put("content",map.get("content").toString());
            video.put("offset",(pageNo-1)*pageSize);
            video.put("limit",pageSize);
            List<ShortVideo> videos=shortVideoMapper.getList(video);
            covertList(videos,null);
            result.put("searchs",videos);
        }
        return result;
    }

    public void covertList(List<ShortVideo> list,String userId){
	    if(list==null||list.size()==0){
	        return;
        }
        for(ShortVideo s:list){
            Map<String,String> video=AliyunVideoUtil.getPlayInfo(s.getVideoId());
            if(video==null){
                continue;
            }
            s.setCoverUrl(video.get("coverURL"));
            s.setVideoUrl(video.get("playURL"));
            if(StringUtils.isNotBlank(userId)){
                ShortVideoLike record=new ShortVideoLike();
                record.setUserId(Integer.parseInt(userId));
                record.setVideoId(s.getId());
                List<ShortVideoLike> likeList=shortVideoLikeMapper.selectByRecord(record);
                if(likeList==null||likeList.size()==0){
                    s.setIsLike(0);
                }else {
                    s.setIsLike(1);
                }
            }else{
                s.setIsLike(0);
            }
//            logger.info("视频用户id{}",s.getUserId());
            User user=userMapper.selectByPrimaryKey(s.getUserId());
            if(StringUtils.isNotBlank(user.getHeadImage())) {
                if (user.getHeadImage().contains("http")) {
                    s.setImageUrl(user.getHeadImage());
                } else {
                    s.setImageUrl(fastdfsServer + user.getHeadImage());
                }
            }
            s.setUserName(user.getName());
            String coverDate= DateUtil.converDate(s.getCreateTime());
            s.setReleaseTime(coverDate);
        }
    }
}
